<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑页</title>
</head>

<body>
    <table>
        <h3>添加或修改博客</h3>
        <tr>
            <td><label>标题</label></td>
            <td><input type="text" name="title"></td>
        </tr>
        <tr>
            <td><label>摘要</label></td>
            <td><input type="text" name="abstract"></td>
        </tr>
        <tr>
            <td><label>内容</label></td>
            <td><input type="text" name="content"></td>
        </tr>
        <tr>
            <td><label>分类</label></td>
            <td><input type="text" name="classify"></td>
        </tr>
        <tr>
            <td><label>作者</label></td>
            <td><input type="text" name="author"></td>
        </tr>
        <tr>
            <td><input type="button" value="保存" onclick="btnSave()"></td>
            <td><input type="button" value="返回" onclick="btnCancle()"></td>
        </tr>
    </table>
    <script src="./js/jquery-3.6.0.min.js"></script>
    <script src="./config/baseUrl.js"></script>
    <script src="./js/api.js"></script>
    <script>
        // 获取url参数 （id）
        function getUrlParams(name) {
            let reg = new RegExp("(^|&)" + name + "=([^&]*)($|&)");
            let r = location.search.substr(1).match(reg);
            if (r !== null) return unescape(r[2]);
            return null;
        }
        // 编辑页面获取数据
        $(function () {
            let id = getUrlParams('id');
            if (id) {
                getProductListById(id).then(res => {
                    let obj = res.data;
                    $('[name=title]').val(obj.title),
                        $('[name=abstract]').val(obj.abstract),
                        $('[name=content]').val(obj.content),
                        $('[name=classify]').val(obj.classify),
                        $('[name=author]').val(obj.author),
                        $('[name=time]').val(obj.time)
                })
            }
        })
        function btnSave() {
            let id = getUrlParams('id');
            let obj = {
                title : $('[name=title]').val(),
                abstract : $('[name=abstract]').val(),
                content : $('[name=content]').val(),
                classify : $('[name=classify]').val(),
                author : $('[name=author]').val(),
                time : $('[name=time]').val()
            }
            if(id){
                updateProduct(id,obj).then(res=>{
                    window.location.href = `./index.html`;
                })
            }else{
                addProduct(id).then(res=>{
                    window.location.href = `./index.html`
                })
            }
        }
        function btnCancle() {
            window.location.href = `./index.html`;
        }
    </script>
</body>

</html>